package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Factory;
import cn.itcast.domain.cargo.FactoryExample;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Date;

@Controller
@Slf4j
@RequestMapping("/cargo/factory")
public class FactoryController extends BaseController {

    @Reference
    private FactoryService factoryService;

    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize){
        log.info("执行查询厂家信息列表");
        // 构造条件对象：根据企业id查询、创建时间降序排序
        FactoryExample factoryExample = new FactoryExample();
        // 降序排序
        factoryExample.setOrderByClause("create_time desc");
        FactoryExample.Criteria criteria = factoryExample.createCriteria();
        PageInfo<Factory> pageInfo = factoryService.findByPage(factoryExample, pageNum, pageSize);
        request.setAttribute("pageInfo",pageInfo);
        return "cargo/factory/factory-list";
    }

    /**
     * 进入添加页面
     */
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "cargo/factory/factory-add";
    }

    /**
     * 添加或修改
     */
    @RequestMapping("/edit")
    public String edit(Factory factory){
        // 设置企业信息（从登陆用户中获取）
        factory.setCompanyId(getLoginCompanyId());
        factory.setCompanyName(getLoginCompanyName());

        // 判断：根据id是否为空判断执行添加还是修改
        if (StringUtils.isEmpty(factory.getId())){
            // 设置创建时间、创建人、创建人的部门
            factory.setCreateTime(new Date());
            factory.setCreateBy(getLoginUser().getId());
            factory.setCreateDept(getLoginUser().getDeptId());
            factory.setUpdateTime(new Date());
            // 添加
            factoryService.save(factory);
        }else {
            // 修改
            factoryService.update(factory);
        }
        return "redirect:/cargo/factory/list";
    }

    /**
     * 进入修改页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model) {
        // 根据id查询
        Factory factory = factoryService.findById(id);
        model.addAttribute("factory", factory);
        return "cargo/factory/factory-update";
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public String delete(String id) {
        factoryService.delete(id);
        return "redirect:/cargo/factory/list";
    }
}
